<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="训练集" prop="trainId">
            <el-input v-model="queryParams.trainId" placeholder="请输入训练集" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="验证集" prop="validId">
            <el-input v-model="queryParams.validId" placeholder="请输入验证集" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="模型" prop="modelId">
            <el-input v-model="queryParams.modelId" placeholder="请输入模型" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:stragyLsc:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:stragyLsc:remove']"
            >批量删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:stragyLsc:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="stragyLscList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="策略名称" align="center" prop="stragyName" />
        <el-table-column label="训练集" align="center">
          <template v-slot="scope">
            {{ trainDataDict.value.find(item => item.value == scope.row.trainId)?.label || trainDataDict}}
          </template>
        </el-table-column>
        <el-table-column label="验证集" align="center" prop="validId">
          <template v-slot="scope">
            {{ validDataDict.value.find(item => item.value == scope.row.validId)?.label || '处理情况未知' }}
          </template>
        </el-table-column>
        <el-table-column label="模型" align="center" prop="modelId">
          <template v-slot="scope">
            {{ modelDataDict.value.find(item => item.value == scope.row.modelId)?.label || '处理情况未知' }}
          </template>
        </el-table-column>
        <el-table-column label="训练状态" align="center" prop="trainStatus">
          <template v-slot="scope">
             <span v-if="scope.row.trainStatus == 0">
              {{ trainStatusDict.find(item => item.value == scope.row.trainStatus)?.label || '处理情况未知' }}
             </span>
            <span v-else style="color: #1ab394">
               {{ trainStatusDict.find(item => item.value == scope.row.trainStatus)?.label || '处理情况未知' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:stragyLsc:edit']">修改</el-button>
            </el-tooltip>
            <el-tooltip content="配置" placement="top">
              <el-button link type="info" icon="Setting" @click="handleConfig(scope.row)" v-hasPermi="['system:stragyLsc:edit']">配置</el-button>
            </el-tooltip>
            <el-tooltip content="训练" placement="top">
              <el-button link type="success" icon="Aim" @click="handleTraing(scope.row)" v-hasPermi="['system:stragyLsc:edit']">训练</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:stragyLsc:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="stragyLscFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="策略名称" prop="stragyName">
          <el-input v-model="form.stragyName" placeholder="请输入策略名称" style="width: 345px" />
        </el-form-item>
        <el-form-item label="训练集" prop="trainId">
          <el-select v-model="form.trainId" placeholder="请选择训练集" style="width: 345px">
            <el-option v-for="dict in trainDataDict.value" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="验证集" prop="validId">
          <el-select v-model="form.validId" placeholder="请选择验证集" :disabled="isNeedV">
            <el-option v-for="dict in validDataDict.value" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <el-checkbox border style="margin-left: 10px" @change="handleChangeV">无需验证集</el-checkbox>
        </el-form-item>
        <el-form-item label="模型" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择模型" style="width: 345px">
            <el-option v-for="dict in modelDataDict.value" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogS.title" v-model="dialogS.visible" width="600px" append-to-body>
      <train-config :stragy-id="stragyId" v-if="dialogS.visible" />
    </el-dialog>
  </div>
</template>

<script setup name="StragyLsc" lang="ts">
import { listStragyLsc, getStragyLsc, delStragyLsc, addStragyLsc, updateStragyLsc } from '@/api/lsc/strategy';
import { StragyLscVO, StragyLscQuery, StragyLscForm } from '@/api/lsc/strategy/types';
import { listLscModel } from "@/api/lsc/model";
import { LscVO } from "@/api/lsc/model/types";
import { listLsc } from "@/api/lsc/dataset";
import { LscDataVO } from "@/api/lsc/dataset/types";
import router from "@/router";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const stragyLscList = ref<StragyLscVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const isNeedV = ref(false);
const trainStatusDict = ref([
  {label: "未训练", value: 0},
  {label: "已训练", value: 1},
])
const queryFormRef = ref<ElFormInstance>();
const stragyLscFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogS = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StragyLscForm = {
  id: undefined,
  trainId: undefined,
  validId: undefined,
  trainStatus: undefined,
  modelId: undefined,
}
const data = reactive<PageData<StragyLscForm, StragyLscQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    trainId: undefined,
    validId: undefined,
    trainStatus: undefined,
    modelId: undefined,
    stragyName: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    trainId: [
      { required: true, message: "训练集id不能为空", trigger: "blur" }
    ],
    validId: [
      { required: true, message: "验证集id不能为空", trigger: "blur" }
    ],
    trainStatus: [
      { required: true, message: "训练状态不能为空", trigger: "change" }
    ],
    modelId: [
      { required: true, message: "模型id不能为空", trigger: "blur" }
    ],
    stragyName: [
      { required: true, message: "策略名称不能为空", trigger: "blur" }
    ],
  }
});


const { queryParams, form, rules } = toRefs(data);

interface DataDict {
  value: { label: string; value: string | number }[];
}

const modelDataDict = reactive<DataDict>({
  value: []
});

const trainDataDict = reactive<DataDict>({
  value: []
});

const validDataDict = reactive<DataDict>({
  value: []
});

onMounted(() => {
  init()
})
const init = () => {
  getModelList()
  getDatasetList()
}

const lscList = ref<LscVO[]>([]);
const lscDataList = ref<LscDataVO[]>([]);
const getModelList = async () => {
  const res = await listLscModel(Object.assign({ modelStatus: 1 }));
  lscList.value = res.rows;
  lscList.value.forEach(model => {
    modelDataDict.value.push({label: model.modelName, value: String(model.id)})
  })
}
const handleChangeV = () => {
  isNeedV.value = !isNeedV.value;
  if (isNeedV.value) {
    form.value.validId = "10201"
  } else {
    form.value.validId = undefined
  }
}
const getDatasetList = async () => {
  const res = await listLsc(Object.assign({ status: 1 }));
  lscDataList.value = res.rows;
  lscDataList.value.forEach(data => {
    if (data.dataType === '0') {
      trainDataDict.value.push({label: data.dataName, value: String(data.id)})
      console.log("train:", lscDataList.value)
    }
    if (data.dataType === '1') {
      validDataDict.value.push({label: data.dataName, value: String(data.id)})
      console.log("valid:", lscDataList.value)
    }
  })
  validDataDict.value.push({label: "无需验证集", value: String(10201)})
}

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStragyLsc(queryParams.value);
  stragyLscList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  stragyLscFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: StragyLscVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加训练策略";
}
const stragyId = ref("")
const handleConfig = (row?: StragyLscVO) => {
  stragyId.value = String(row?.id);
  dialogS.visible = true;
  dialogS.title = "配置训练策略";
}

const handleTraing = (row?: StragyLscVO) => {
  localStorage.setItem("stragyId", String(row?.id))
  localStorage.setItem("stragyName", String(row?.stragyName))
  router.push("/lsc/train/training")
}

/** 修改按钮操作 */
const handleUpdate = async (row?: StragyLscVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getStragyLsc(_id);
  Object.assign(form.value, res.data);
  if (res.data.validId === 10201) {
    form.value.validId = "10201"
  }
  dialog.visible = true;
  dialog.title = "修改训练策略";
}

/** 提交按钮 */
const submitForm = () => {
  form.value.trainStatus = 0;
  stragyLscFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStragyLsc(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addStragyLsc(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: StragyLscVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delStragyLsc(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/stragyLsc/export', {
    ...queryParams.value
  }, `stragyLsc_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
